<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="40%"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入任务名称"/>
      </el-form-item>
      
      <el-form-item label="任务类型" prop="task_type">
        <el-radio-group v-model="form.task_type">
          <el-radio value="interval">定时任务</el-radio>
          <el-radio value="crontab">周期任务</el-radio>
          <el-radio value="clock">时钟任务</el-radio>
          <el-radio value="once">一次性任务</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <!-- 周期任务配置 -->
      <template v-if="form.task_type === 'crontab'">
        <el-form-item label="分钟" prop="crontab_minute">
          <el-input v-model="form.crontab_minute" placeholder="分钟 (0-59, *, */5)"/>
          <div class="form-tips">
            <el-text type="info" size="small">例如: 0 表示整点, */5 表示每5分钟, * 表示每分钟</el-text>
          </div>
        </el-form-item>
        
        <el-form-item label="小时" prop="crontab_hour">
          <el-input v-model="form.crontab_hour" placeholder="小时 (0-23, *, */2)"/>
          <div class="form-tips">
            <el-text type="info" size="small">例如: 9 表示9点, */2 表示每2小时, * 表示每小时</el-text>
          </div>
        </el-form-item>
        
        <el-form-item label="星期" prop="crontab_day_of_week">
          <el-input v-model="form.crontab_day_of_week" placeholder="星期 (0-6, *, MON-FRI)"/>
          <div class="form-tips">
            <el-text type="info" size="small">例如: 1 表示周一, MON-FRI 表示工作日, * 表示每天</el-text>
          </div>
        </el-form-item>
        
        <el-form-item label="日期" prop="crontab_day_of_month">
          <el-input v-model="form.crontab_day_of_month" placeholder="日期 (1-31, *, */3)"/>
          <div class="form-tips">
            <el-text type="info" size="small">例如: 1 表示每月1号, */3 表示每3天, * 表示每天</el-text>
          </div>
        </el-form-item>
        
        <el-form-item label="月份" prop="crontab_month_of_year">
          <el-input v-model="form.crontab_month_of_year" placeholder="月份 (1-12, *, */3)"/>
          <div class="form-tips">
            <el-text type="info" size="small">例如: 1 表示1月, */3 表示每3个月, * 表示每月</el-text>
          </div>
        </el-form-item>
      </template>
      
      <!-- 定时任务配置 -->
      <template v-if="form.task_type === 'interval'">
        <el-form-item label="执行间隔" prop="interval_time">
          <el-input-number v-model="form.interval_time" :min="1" placeholder="请输入执行间隔"/>
        </el-form-item>
        
        <el-form-item label="时间单位" prop="interval_unit">
          <el-select v-model="form.interval_unit" placeholder="请选择时间单位">
            <el-option label="秒" value="seconds"/>
            <el-option label="分钟" value="minutes"/>
            <el-option label="小时" value="hours"/>
            <el-option label="天" value="days"/>
          </el-select>
        </el-form-item>
      </template>
      
      <!-- 时钟任务配置 -->
      <template v-if="form.task_type === 'clock'">
        <el-form-item label="执行时间" prop="clock_time">
          <el-date-picker
            v-model="form.clock_time"
            type="datetime"
            placeholder="选择执行时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </template>
      
      <el-form-item label="任务描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入任务描述"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from "vue";
import requestUtil from "@/util/request";
import { ElMessage } from 'element-plus';

const props = defineProps({
  id: {
    type: Number,
    default: -1,
    required: true
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogVisible: {
    type: Boolean,
    default: false,
    required: true
  }
});

// 表单数据
const form = ref({
  id: -1,
  name: '',
  task_type: 'crontab',
  
  // 周期任务配置
  crontab_minute: '*',
  crontab_hour: '*',
  crontab_day_of_week: '*',
  crontab_day_of_month: '*',
  crontab_month_of_year: '*',
  
  // 定时任务配置
  interval_time: 1,
  interval_unit: 'minutes',
  
  // 时钟任务配置
  clock_time: '',
  
  description: ''
});

// 表单验证规则
const rules = ref({
  name: [{ required: true, message: "任务名称不能为空", trigger: "blur" }],
  task_type: [{ required: true, message: "任务类型不能为空", trigger: "change" }],
  
  // 定时任务验证
  interval_time: [{ required: true, message: "执行间隔不能为空", trigger: "blur" }],
  interval_unit: [{ required: true, message: "时间单位不能为空", trigger: "change" }],
  
  // 时钟任务验证
  clock_time: [
    { required: true, message: "执行时间不能为空", trigger: "change" },
    { 
      validator: (rule, value, callback) => {
        if (value && new Date(value) < new Date()) {
          callback(new Error('执行时间不能早于当前时间'));
        } else {
          callback();
        }
      }, 
      trigger: "change" 
    }
  ]
});

const formRef = ref(null);

// 初始化表单数据
const initFormData = async (id) => {
  try {
    const res = await requestUtil.get("tasks/task_definitions/" + id + '/');
    
    // 基础字段
    form.value.id = res.id;
    form.value.name = res.name;
    form.value.task_type = res.task_type;
    form.value.description = res.description;
    
    // 根据任务类型解析调度数据
    if (res.task_type === 'crontab' && res.crontab_detail) {
      form.value.crontab_minute = res.crontab_detail.minute;
      form.value.crontab_hour = res.crontab_detail.hour;
      form.value.crontab_day_of_week = res.crontab_detail.day_of_week;
      form.value.crontab_day_of_month = res.crontab_detail.day_of_month;
      form.value.crontab_month_of_year = res.crontab_detail.month_of_year;
    } else if (res.task_type === 'interval' && res.interval_detail) {
      form.value.interval_time = res.interval_detail.every;
      form.value.interval_unit = res.interval_detail.period;
    } else if (res.task_type === 'clock' && res.clocked_detail) {
      form.value.clock_time = res.clocked_detail.clocked_time;
    }
  } catch (err) {
    console.error("获取任务定义信息失败", err);
    ElMessage.error('获取任务定义信息失败: ' + err);
  }
};

// 监听对话框可见性变化
watch(
  () => props.dialogVisible,
  () => {
    let id = props.id;
    if (id !== -1) {
      initFormData(id);
    } else {
      // 重置表单
      form.value = {
        id: -1,
        name: '',
        task_type: 'crontab',
        
        // 周期任务配置
        crontab_minute: '*',
        crontab_hour: '*',
        crontab_day_of_week: '*',
        crontab_day_of_month: '*',
        crontab_month_of_year: '*',
        
        // 定时任务配置
        interval_time: 1,
        interval_unit: 'minutes',
        
        // 时钟任务配置
        clock_time: '',
        
        description: ''
      };
    }
  }
);

const emits = defineEmits(['update:modelValue', 'initTaskDefinitionList']);

// 关闭对话框
const handleClose = () => {
  emits('update:modelValue', false);
};

// 提交表单
const handleConfirm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = {
          name: form.value.name,
          task_type: form.value.task_type,
          description: form.value.description
        };
        
        // 如果是更新操作，添加id
        if (form.value.id !== -1) {
          formData.id = form.value.id;
        }
        
        // 根据任务类型构造对应的调度数据
        if (formData.task_type === 'crontab') {
          formData.crontab_data = {
            minute: form.value.crontab_minute,
            hour: form.value.crontab_hour,
            day_of_week: form.value.crontab_day_of_week,
            day_of_month: form.value.crontab_day_of_month,
            month_of_year: form.value.crontab_month_of_year,
            timezone: 'Asia/Shanghai'
          };
        } else if (formData.task_type === 'interval') {
          formData.interval_data = {
            every: form.value.interval_time,
            period: form.value.interval_unit
          };
        } else if (formData.task_type === 'clock') {
          formData.clocked_data = {
            clocked_time: form.value.clock_time
          };
        }
        
        if (formData.id === undefined) {
          // 新增
          await requestUtil.post("tasks/task_definitions/", formData);
          ElMessage.success("添加成功");
        } else {
          // 更新
          await requestUtil.patch("tasks/task_definitions/" + formData.id + "/", formData);
          ElMessage.success("更新成功");
        }
        
        handleClose();
        emits('initTaskDefinitionList');
      } catch (error) {
        console.error(error);
        const errorMsg = error.response?.data || error.error || '未知错误';
        const errorStr = typeof errorMsg === 'object' ? JSON.stringify(errorMsg) : errorMsg;
        ElMessage.error("操作失败: " + errorStr);
      }
    } else {
      ElMessage.warning("请正确填写表单");
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
.form-tips {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style>
